package com.chindeo.h5.x5.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.FrameLayout;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chindeo.h5.R;
import com.chindeo.h5.x5.H5;
import com.chindeo.h5.x5.H5PrivateUtil;
import com.chindeo.h5.x5.X5Helper;
import com.chindeo.h5.x5.view.UnMeasure;
import com.chindeo.h5.x5.view.X5WebView;
import com.chindeo.repository.RepositoryComponent;
import com.chindeo.repository.util.AppConfigManager;
import com.lazylibs.component.ui.fragment.BaseSupportFragment;
import com.lazylibs.util.ToastUtils;
import com.lazylibs.weight.skeleton.IViewSkeleton;
import com.lazylibs.weight.skeleton.SimpleStateView;
import com.lazylibs.weight.skeleton.Skeleton;
import com.lazylibs.weight.skeleton.ViewState;
import com.tencent.smtt.sdk.WebSettings;

import java.util.LinkedHashMap;
import java.util.Map;

public class H5Fragment extends BaseSupportFragment {

    protected View close;
    protected X5Helper helper;
    protected IViewSkeleton skeleton;
    protected H5.Params params;
    protected Map<String, String> header;
    protected boolean isLogining = false;

    public H5Fragment setSkeleton(IViewSkeleton skeleton) {
        this.skeleton = skeleton;
        return this;
    }

    public static H5Fragment newInstance(Bundle extras, IViewSkeleton skeleton) {
        return new H5Fragment().setParams(new H5.Params(extras)).setSkeleton(skeleton);
    }

    public static H5Fragment newInstance(Bundle extras) {
        return new H5Fragment().setParams(new H5.Params(extras));
    }

    public <T extends H5Fragment> T setParams(H5.Params params) {
        this.params = params;
        return (T) this;
    }

    protected void initView() {
        helper = getX5Helper();
        helper.getWebView().getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        initCloseView();
    }

    protected void initCloseView() {
        if (params.isNeedHeader()) {
            close = root.findViewById(R.id.close);
            if (close != null) {
                close.setOnClickListener(v -> {
                    Activity activity = X5WebView.getActivity(v.getContext());
                    if (activity != null) {
                        activity.finish();
                    }
                });
            }
        }
    }

    public void reload() {
        loadUrl();
    }

    public void windowRefresh() {
        if (helper != null && helper.getWebView() != null) {
            helper.getWebView().loadUrl("javascript:window.refresh();");
        }
    }

    protected void loadUrl() {
        if (helper != null && helper.getWebView() != null) {
            helper.getWebView().loadUrl(getUrl(), header());
        }
    }

    protected String getUrl() {
        String url = params != null ? params.url : "";
        return url;
    }

    protected String getUserAgent() {
        if (TextUtils.isEmpty(params.getUserAgent())) {
            params.setUserAgent(AppConfigManager.get().getUserAgent());
        }
        return params.getUserAgent();
    }


    protected Object getImpl() {
        return new H5.IBridge() {
            @Override
            public Context getContext() {
                return root.getContext();
            }

            @Override
            public H5.Params getParams() {
                return params;
            }


            @JavascriptInterface
            public void openBrowser(String url) {//H5调用APP打开默认浏览器url: 需要打开的url地址
                if (getContext() == null) return;
                H5.openBrowser(getContext(), url);
            }

            @JavascriptInterface
            public void openWebview(String url, String title) {//title如果有传就显示
                H5.openH5(getContext(), H5.getBaseExtras(title, url));
            }

            @JavascriptInterface
            public void back() {//关闭当前webview
                if (getContext() == null) return;
                Activity activity = (Activity) getContext();
                if (activity != null) {
                    activity.finish();
                }
            }


            @JavascriptInterface
            public int getStatusBarHeight() {//获取状态栏高度
                Context context = getContext() == null ? RepositoryComponent.getInstance() : getContext();
                return H5PrivateUtil.getStatusBarHeight(context);
            }

            @JavascriptInterface//放大图片
            public void showToast(String msg) {
                if (getContext() == null) return;
                ToastUtils.showShort(getContext(), msg);
            }

        };
    }

    protected X5Helper getX5Helper() {
        X5Helper.Builder builder = new X5Helper.Builder()
                .setUserAgent(getUserAgent())
                .setJsInterface(new LinkedHashMap<String, Object>() {
                    {
                        put(AppConfigManager.get().jsName, getImpl());
                    }
                })
                .setGame(true)
                .setHandler(x5WebView -> {
                    if (header() != null) {
                        x5WebView.loadUrl(getUrl(), header());
                    } else {
                        x5WebView.loadUrl(getUrl());
                    }
                });
        if (skeleton != null) {
            builder.action1(skeleton);
        } else {
            builder.action1(new SimpleStateView() {
                @Override
                public View onCreateView(Context context, ViewGroup container, int viewState) {
                    if (viewState == ViewState.EMPTY) {
                        return LayoutInflater.from(context).inflate(R.layout.tpl_h5_404, container, false);
                    }
                    return Skeleton.getStateView().onCreateView(context, container, viewState);
                }
            });
        }
        if (params.isNeedScroll()) {
            return builder.build((FrameLayout) root.findViewById(R.id.fl_h5));
        } else {
            FrameLayout parent = root.findViewById(R.id.fl_h5);
            X5WebView webView = new UnMeasure(parent.getContext());
            parent.addView(webView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT));
            return builder.build(webView);
        }
    }

    protected Map<String, String> header() {
        if (header == null) {
            header = JSON.parseObject(params.getHeadString(), new TypeReference<Map<String, String>>() {
            });
        }
        return header;
    }

    @Override
    public void init(Bundle bundle) {
        if (!H5.requireParams(params)) {
            return;
        }
        initView();
    }

    BroadcastReceiver pReceiver;


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (pReceiver != null) {
            LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(pReceiver);
        }
        X5Helper.destroy(helper);
        Log.e(getClass().getSimpleName(), "onDestroy");
    }

    @Override
    public void initData() {
        if (getActivity() != null) {
            loadUrl();
        }
    }

    @Override
    public int layoutRes() {
        return R.layout.fragment_h5_web;
    }


}
